package com.mjk.common.tools.xml.conver.impl;

import com.google.gson.internal.LinkedTreeMap;
import com.mjk.common.util.ObjectUtils;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class LinkedTreeMapConverter implements Converter {
    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        LinkedTreeMap<?, ?> map = (LinkedTreeMap<?, ?>) source;
        for (Object key : map.keySet()) {
            Object value = map.get(key);
            writer.startNode(key.toString());
            if (ObjectUtils.isNotEmpty(value)) {
                writer.setValue(value.toString());
            } else {
                writer.setValue("");
            }
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        LinkedTreeMap<Object, Object> map = new LinkedTreeMap<>();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            String key = reader.getNodeName();
            String value = reader.getValue();
            map.put(key, value);
            reader.moveUp();
        }
        return map;
    }

    @Override
    public boolean canConvert(Class type) {
        return type.equals(LinkedTreeMap.class);
    }
}
